package com.company.OfferGuide;

import java.util.ArrayList;

public class 顺时针打印矩阵 {

    public int[] spiralOrder(int[][] matrix) {
        if (matrix == null) return new int[]{};
        if (matrix.length == 0) return new int[]{};
        if (matrix[0].length == 0) return new int[]{};


        ArrayList<Integer> list = new ArrayList<>();
        int left = 0,right = matrix[0].length;
        int top = 0,down = matrix.length ;
        while (true){

            for (int i = left; i <= right; i++) {
                list.add(matrix[top][i]);
            }
            top++;
            if (top > down) break;

            for (int i = top; i <= down; i++) {
                list.add(matrix[i][right]);
            }
            right--;
            if (left > right) break;
            for (int i = right; i >= left; i--) {
                list.add(matrix[down][i]);
            }
            down--;
            if (top > down) break;

            for (int i = down; i >= top ; i--) {
                list.add(matrix[i][left]);
            }
            left++;
            if (left > right) break;
        }

        int[] ints = new int[list.size()];

        for (int i = 0; i < list.size(); i++) {
            ints[i] = list.get(i);
        }

        return ints;
    }

}
